package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-21
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper,Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private IoTDAClient client;

    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectDeviceById(id);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 注册设备
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //判断设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
        if(count(queryWrapper) > 0){
            throw new BaseException("设备名称已存在，请重新输入");
        }
        //检验设备标识码是否重复
        LambdaQueryWrapper<Device> queryWrapperNodeId = new LambdaQueryWrapper<>();
        queryWrapperNodeId.eq(Device::getNodeId, deviceDto.getNodeId());
        if(count(queryWrapperNodeId) > 0){
            throw new BaseException("设备标识码已存在，请重新输入");
        }

        //校验同一位置是否绑定了同一类产品
        LambdaQueryWrapper<Device> condition = new LambdaQueryWrapper<>();
        condition.eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation());
        if (count(condition) > 0) {
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }

        //iot中新增设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withProductId(deviceDto.getProductKey());
        body.withDeviceName(deviceDto.getDeviceName());
        body.withNodeId(deviceDto.getNodeId());
        request.withBody(body);
        AuthInfo authInfo = new AuthInfo();
        //秘钥
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.withSecret(secret);
        body.setAuthInfo(authInfo);
        AddDeviceResponse response;
        try {
            response = client.addDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }

        //设备数据保存到数据库
        //属性拷贝
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        //设备id、设备绑定状态
        device.setIotId(response.getDeviceId());
        //秘钥
        device.setSecret(secret);

        //根据productKey获取产品名称并保存
        String productName = getProductNameByKey(deviceDto.getProductKey());
        if (productName != null) {
            device.setProductName(productName);
            System.out.println("设置产品名称: " + productName);
        }

        //在数据库中新增设备
        try {
            save(device);
        } catch (Exception e) {
            throw new BaseException("同一个位置不能绑定同类型的产品");
        }
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        // 先更新华为云IoT平台的设备信息
        try {
            UpdateDeviceRequest request = new UpdateDeviceRequest();
            request.withDeviceId(device.getIotId());
            
            UpdateDevice body = new UpdateDevice();
            // 设置设备名称
            if (device.getDeviceName() != null) {
                body.withDeviceName(device.getDeviceName());
            }
            // 设置设备描述
            if (device.getDeviceDescription() != null) {
                body.withDescription(device.getDeviceDescription());
            }
            
            request.withBody(body);
            UpdateDeviceResponse response = client.updateDevice(request);
            
            if (response.getHttpStatusCode() != 200) {
                throw new BaseException("华为云IoT - 修改设备失败");
            }
            
        } catch (Exception e) {
            System.out.println("华为云IoT - 修改设备失败: " + e.getMessage());
            throw new BaseException("华为云IoT - 修改设备失败: " + e.getMessage());
        }
        
        // 更新本地数据库
        device.setUpdateTime(DateUtils.getNowDate());
        return deviceMapper.updateDevice(device);
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        // 先从华为云IoT平台删除设备
        for (Long id : ids) {
            Device device = deviceMapper.selectDeviceById(id);
            if (device != null && device.getIotId() != null) {
                try {
                    DeleteDeviceRequest request = new DeleteDeviceRequest();
                    request.withDeviceId(device.getIotId());
                    
                    DeleteDeviceResponse response = client.deleteDevice(request);
                    
                    if (response.getHttpStatusCode() != 204) {
                        System.out.println("华为云IoT - 删除设备失败, 设备ID: " + device.getIotId());
                        // 注意：这里不抛异常，因为即使华为云删除失败，也要删除本地数据
                    }
                    
                } catch (Exception e) {
                    System.out.println("华为云IoT - 删除设备异常: " + e.getMessage());
                    // 注意：这里不抛异常，因为即使华为云删除失败，也要删除本地数据
                }
            }
        }
        
        // 删除本地数据库记录
        return deviceMapper.deleteDeviceByIds(ids);
    }

    /**
     * 根据iotId删除设备（按照老师接口文档）
     *
     * @param iotId 设备IoT ID
     * @param productKey 产品Key
     * @return 结果
     */
    public int deleteDeviceByIotId(String iotId, String productKey)
    {
        // 先从华为云IoT平台删除设备
        try {
            DeleteDeviceRequest request = new DeleteDeviceRequest();
            request.withDeviceId(iotId);
            
            DeleteDeviceResponse response = client.deleteDevice(request);
            
            if (response.getHttpStatusCode() != 204) {
                throw new BaseException("华为云IoT - 删除设备失败");
            }
            
        } catch (Exception e) {
            System.out.println("华为云IoT - 删除设备失败: " + e.getMessage());
            throw new BaseException("华为云IoT - 删除设备失败: " + e.getMessage());
        }
        
        // 删除本地数据库记录
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);
        queryWrapper.eq(Device::getProductKey, productKey);
        
        Device device = deviceMapper.selectOne(queryWrapper);
        if (device != null) {
            return deviceMapper.deleteDeviceById(device.getId());
        }
        
        return 0;   
    }

    /**
     * 删除设备信息
     *
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteDeviceById(id);
    }

    /**
     * 根据产品Key获取产品名称
     * @param productKey 产品Key
     * @return 产品名称
     */
    private String getProductNameByKey(String productKey) {
        try {
            // 从Redis缓存中获取产品列表
            String productListJson = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
            if (StringUtils.isNotEmpty(productListJson)) {
                // 使用Hutool的JSONUtil解析JSON
                cn.hutool.json.JSONArray productArray = JSONUtil.parseArray(productListJson);
                for (int i = 0; i < productArray.size(); i++) {
                    cn.hutool.json.JSONObject product = productArray.getJSONObject(i);
                    if (productKey.equals(product.getStr("productKey"))) {
                        return product.getStr("productName");
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("获取产品名称失败: " + e.getMessage());
        }
        return null;
    }

    /**
     * 查询所有产品列表
     *
     * @return 产品列表
     */
    @Override
    public List<ProductVo> allProduct() {
        //从redis中查询数据
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        //如果数据为空，则返回一个空集合
        if(StringUtils.isEmpty(jsonStr)){
            return Collections.emptyList();
        }
        //解析数据，并返回
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 查询设备详情
     *
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查询数据库
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)) {
            return null;
        }

        //调用华为云物联网接口
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            System.out.println("物联网接口 - 查询设备详情，调用失败: " + e.getMessage());
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }

        //属性拷贝
        DeviceDetailVo deviceVo = BeanUtil.toBean(device, DeviceDetailVo.class);

        // 设置设备状态
        deviceVo.setDeviceStatus(response.getStatus());
        
        // 设置节点类型（先设置默认值，后续通过调试确定正确的API调用）
        deviceVo.setNodeType("直连设备");
        
        // 设置认证类型（先设置默认值，后续通过调试确定正确的API调用）
        deviceVo.setAuthType("密钥");
        
        // 设置激活时间
        String activeTimeStr = response.getActiveTime();
        if(StringUtils.isNotEmpty(activeTimeStr)){
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceVo.setActiveTime(activeTime);
        }

        return deviceVo;
    }

    /**
     * 查询设备上报数据
     *
     * @param iotId
     * @return
     */
    @Override
    public AjaxResult queryServiceProperties(String iotId) {

        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询设备上报数据，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if(CollUtil.isEmpty(shadow)){
            List<Object> emptyList = Collections.emptyList();
            return AjaxResult.success(emptyList);
        }
        //返回数据
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());

        List<Map<String,Object>> list = new ArrayList<>();

        //处理上报时间日期
        LocalDateTime activeTime =  LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        jsonObject.forEach((k,v)->{
            Map<String,Object> map = new HashMap<>();
            map.put("functionId",k);
            map.put("value",v);
            map.put("eventTime",eventTime);
            list.add(map);
        });

        return AjaxResult.success(list);

    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置条数
        listProductsRequest.setLimit(50);
        //发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if(response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        
        // 将华为云数据转换为ProductVo格式
        List<ProductVo> productVoList = new ArrayList<>();
        if (response.getProducts() != null) {
            for (var productSummary : response.getProducts()) {
                ProductVo productVo = new ProductVo();
                productVo.setProductKey(productSummary.getProductId());  // 华为云的productId映射为前端的productKey
                productVo.setProductName(productSummary.getName());      // 华为云的name映射为前端的productName
                productVoList.add(productVo);
            }
        }
        
        //存储转换后的ProductVo列表到redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(productVoList));
    }
}
